package com.cl.ks.flow.handler;

import com.alibaba.fastjson.JSON;
import com.cl.spark.dto.SparkResult;
import com.cl.ks.entity.KsFlowGraph;
import com.cl.ks.entity.SparkNode;
import com.cl.ks.flow.KsFlowGraphHandler;
import com.cl.ks.flow.base.BaseFlowNodeHandler;
import com.cl.ks.flow.enums.NodeHandlerEnum;
import com.cl.ks.service.KsFlowGraphService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutionException;

@Component
public class KsFlowGraphChildHandler extends BaseFlowNodeHandler {
    private final KsFlowGraphService ksFlowGraphService;

    @Lazy
    @Autowired
    private KsFlowGraphHandler ksFlowGraphHandler;

    public KsFlowGraphChildHandler(KsFlowGraphService ksFlowGraphService) {
        this.ksFlowGraphService = ksFlowGraphService;
    }

    @Override
    public SparkResult process(BaseFlowNodeHandler.ProcessParam processParam) {
        Optional<KsFlowGraph> ksFlowGraphChildOptional = ksFlowGraphService.findById((Integer) processParam.getSparkNode().getNodeExpression().get("id"));
        if (!ksFlowGraphChildOptional.isPresent()) {
            throw new RuntimeException("流程图不存在");
        }
        KsFlowGraph ksFlowGraphChild = ksFlowGraphChildOptional.get();
        ksFlowGraphChild.setCreatedBy(processParam.getKsFlowGraph().getCreatedBy());
        ksFlowGraphChild.setCreatedByShowName(processParam.getKsFlowGraph().getCreatedByShowName());
        SparkNode childSparkNode = JSON.parseObject(ksFlowGraphChild.getSparkNodeJson(), SparkNode.class);
        childSparkNode.setInputSparkResultList(processParam.getSparkNode().getInputSparkResultList());
        ksFlowGraphChild.setSparkNode(childSparkNode);
        ksFlowGraphChild.setSaveKsFlowResultFlag(false);
        Map<String, SparkResult> inputSparkResult = null;
        try {
            inputSparkResult = ksFlowGraphHandler.handleKsFlowGraph(ksFlowGraphChild).get().getInputSparkResultList();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }

        if (inputSparkResult != null && !inputSparkResult.values().isEmpty()) {
             SparkResult sparkResult = inputSparkResult.values().stream().findFirst().get();
            return sparkResult;
        }
        return SparkResult.failed("子流程无结果");
    }

    @Override
    public NodeHandlerEnum getType() {
        return NodeHandlerEnum.KS_FLOW_GRAPH_CHILD;
    }
}
